import React, { Component } from 'react';
import styled from 'styled-components';
import { Card, Drawer, Row, Col, Input, Form, Button } from 'antd';
import { connect } from 'dva';
import BaseComponent from '@/components/BaseComponent';
import styles from './index.less';
import { defDrawerWidth } from '@/defaultSettings';
import StandardTable from '@/components/BasicTable';
import AddOrEditViewPlus from '@/pages/SystemInit/UserSetting/AddOrEditViewPlus';

const ImportText = styled.div`
  color: crimson;
  font-size: 16px;
  font-weight: bold;
`;

@connect(({ systeminit, loading }) => ({
  data: systeminit.dataCasUserSync,
  isLoading: loading.effects['systeminit/listByPageCasUserSync'],
  isFinding: loading.effects['systeminit/findUserById'],
  isSaving: loading.effects[('systeminit/addSysUser', 'systeminit/syncTmpUserToSysUser')],
}))
@Form.create()
class CasUserList extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      // 被选中的rows

      selectedRowKeys: [],
      // 默认页数
      currentPage: 1,
      // 默认展示行数
      pageSize: 10,

      // 详情数据
      record: {},
      // 是否显示完善用户信息详情页面
      editViewVisible: false,
    };
  }

  columns = [
    {
      title: '编号',
      sorter: false,
      width: 80,
      key: 'index',
      render: (text, record, index) => {
        return index + 1;
      },
    },
    {
      title: '用户名称',
      sorter: false,
      key: 'username',
      dataIndex: 'username',
    },
    {
      title: '昵称',
      sorter: false,
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '手机号',
      sorter: false,
      key: 'telephone',
      dataIndex: 'telephone',
    },
    {
      title: '操作',
      sorter: false,
      align: 'left',
      width: 100,
      fixed: 'right',
      render: (text, record, index) => {
        return (
          <div>
            <a
              onClick={() => {
                this.handleEditClick(record);
              }}
            >
              完善信息
            </a>
          </div>
        );
      },
    },
  ];

  componentDidMount() {
    this.listByPage({});
  }

  listByPage = (params = {}) => {
    this.execHttp('systeminit/listByPageCasUserSync', {
      currentPage: this.state.currentPage,
      pageSize: this.state.pageSize,
      ...params,
    });
  };

  getTableDataBySearch = () => {
    const { form } = this.props;
    console.log(form);
    const params = {
      search: form.getFieldValue('search'),
    };
    this.listByPage(params);
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form layout="online" ref={this.mForm}>
        <Row gutter={2}>
          <Col span={6}>
            <Form.Item name="search">
              {getFieldDecorator('search')(<Input placeholder="请输入用户名称或昵称或手机号" />)}
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item>
              <Button type="primary" onClick={this.getTableDataBySearch}>
                {' '}
                查询
              </Button>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { onClose, visible, title, data, isLoading } = this.props;
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.selectedRowChangeHandle,
    };
    return (
      <Drawer
        title={title}
        placement="right"
        width={defDrawerWidth}
        closable
        onClose={e => {
          if (onClose) {
            onClose(e);
          }
        }}
        visible={visible}
      >
        <div className={styles.casUserList}>
          <Card bordered>
            <ImportText>请将以下用户信息完善后,再导入系统</ImportText>
          </Card>
          <Card bordered>{this.renderForm()}</Card>
          <Card style={{ marginTop: '16px' }} bordered>
            <StandardTable
              bordered
              rowSelection={rowSelection}
              hasSelection={false}
              onChange={this.handleTableChange}
              selectedRows={selectedRowKeys}
              loading={isLoading}
              data={data}
              columns={this.columns}
              rowKey="id"
              scroll={{ x: 1000 }}
            />
          </Card>
        </div>
        {/* 用户信息编辑页面 */}
        {this.state.editViewVisible ? (
          <AddOrEditViewPlus
            title="用户信息完善"
            visible={this.state.editViewVisible}
            record={this.state.record}
            roleData={this.props.roleData}
            orgData={this.props.orgData}
            onClose={this.handleEditViewClose}
            onSave={this.handleAddOrEditViewPlusOnSave}
            onSubmit={this.handleAddOrEditViewPlusOnSubmit}
          />
        ) : null}
      </Drawer>
    );
  }

  /**
   * 信息编辑页面提交按钮被点击
   * @param data
   */
  handleAddOrEditViewPlusOnSubmit = data => {
    if (this.props.isSaving) {
      return;
    }
    const hide = this.loadingMessage('正在保存...');
    this.execHttp('systeminit/syncTmpUserToSysUser', { ...data })
      .then(res => {
        console.log(res);
        if (hide) {
          hide();
        }
        const { success, data, message } = res;
        if (success) {
          this.successMessage('保存成功');
          this.setState(
            {
              editViewVisible: false,
            },
            () => {
              // 此时需要刷新一下列表
              this.listByPage({});
            }
          );
        } else {
          this.errorMessage(message);
        }
      })
      .catch(err => {
        if (hide) {
          hide();
        }
      });
  };

  /**
   * 信息编辑页面暂存按钮被点击
   * @param data
   */
  handleAddOrEditViewPlusOnSave = data => {
    if (this.props.isSaving) {
      return;
    }
    const hide = this.loadingMessage('正在保存...');
    this.execHttp('systeminit/addSysUser', { ...data })
      .then(res => {
        if (hide) {
          hide();
        }
        const { success, data } = res;
        if (success) {
          this.successMessage('保存成功');
        }
      })
      .catch(err => {
        if (hide) {
          hide();
        }
      });
  };
  selectedRowChangeHandle = data => {
    this.setState({
      selectedRowKeys: data,
    });
  };
  /**
   * 完善用户信息页面关闭
   */
  handleEditViewClose = () => {
    this.setState({
      editViewVisible: false,
    });
  };

  /**
   * table转台改变
   * @param pagination
   * @param filtersArg
   * @param sorter
   */
  handleTableChange = (pagination, filtersArg, sorter) => {
    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    this.setState({
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    });

    this.listByPage(params);
  };

  /**
   * 编辑按钮被点击
   * @param record
   */
  handleEditClick = record => {
    if (this.props.isFinding) {
      return;
    }
    const hide = this.loadingMessage('加载中...');
    // 此时先要读取一次临时表中的数据
    this.execHttp('systeminit/findUserById', { id: record.id })
      .then(resp => {
        if (hide) {
          hide();
        }
        const { success, data } = resp;
        if (success) {
          const { record: rd } = data;
          if (rd) {
            // record存在
            this.setState({
              record: rd,
              editViewVisible: true,
            });
          } else {
            // record不存在,则需要先创建一条数据
            this.setState({
              record: {
                id: record.id,
                nickname: record.name,
                mobile: record.telephone,
                username: record.username,
                status: 1,
              },
              editViewVisible: true,
            });
          }
        }
      })
      .catch(err => {
        if (hide) {
          hide();
        }
      });
  };
}

export default CasUserList;
